package com.jq.aution.controller;

import com.jq.aution.common.Define;
import com.jq.aution.controller.model.UserLoginForm;
import com.jq.aution.controller.model.UserRegisterForm;
import com.jq.aution.model.UserInfo;
import com.jq.aution.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/user")
public class LoginController {
    @Autowired
    UserInfoService userInfoService;

    @RequestMapping("/test3")
    public String test3(){
        System.out.println("123");
        //return new ModelAndView("test");
        return "test";
    }

    @RequestMapping("/test2")
    public ModelAndView test2(Model model){
        System.out.println("123");
        model.addAttribute("aaa","1234");
        return new ModelAndView("test");
    }

    /**
     * 用户登录
     * @param userLoginForm
     * @return
     */
    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request, @ModelAttribute UserLoginForm userLoginForm){
        if(userInfoService.login(userLoginForm.getUserName(),userLoginForm.getUserPassword())){
            UserInfo userInfo=userInfoService.loadUserByUsername(userLoginForm.getUserName());

            HttpSession session=request.getSession();
            session.setAttribute("userId",userInfo.getUserId());

            return "redirect:/index/products";
        }
        return "error";
    }

    /**
     * 用户注册
     * @param userRegisterForm
     * @return
     */
    @RequestMapping(value = "/register")
    public String register(@ModelAttribute UserRegisterForm userRegisterForm){
        //System.out.println(userRegisterForm.getUserType());
        if(userInfoService.register(userRegisterForm.getUserName(),userRegisterForm.getUserPassword(),userRegisterForm.getUserType())){
            return "redirect:/index/login";//重定向
        }
        return "error";
    }

    /**
     * 用户退出
     * @param session
     * @return
     */
    @RequestMapping(value = "/exit")
    public String exit(HttpSession session){
        session.setAttribute("userType",null);
        return "redirect:/index/login";
    }
}
